<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    custom-class="page-dialog sys-user-dialog"
  >
    <el-form
      ref="sysUserForm"
      :model="form"
      label-position="right"
      label-width="100px"
      class="page-form"
      style="width: 100%;">

      <el-form-item label="商品名称 " prop="username">
        <el-input v-model="form.productName" placeholder="请输入商品名称" clearable :readonly="!isAdd"/>
      </el-form-item>

      <el-form-item label="商品图片" prop="phone">
        <div class="upload-container">
          <p class="img-container" clearable>
            <img class="head" :src="form.images" alt="">
          </p>
          <el-upload
            ref="upload"
            name="img"
            class="upload-demo"
            drag
            action=""
            :multiple="false"
            :auto-upload="false"
            :file-list="uploadFileList"
            :show-file-list="false"
            accept="image/jpeg,image/png,image/jpg"
            :http-request="handleUpload"
            :before-upload="handleBeforeUpload"
            :on-change="handleChange"
            :on-error="handleError">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="商品类别编号" prop="phone">
        <el-input v-model="form.categoryId" placeholder="请输入类别编号" clearable :readonly="isDetail"/>
      </el-form-item>
      <el-form-item label="市场价" prop="phone">
        <el-input v-model="form.originalPrice" placeholder="请输入市场价" clearable :readonly="isDetail"/>
      </el-form-item>
      <el-form-item label="会员价" prop="phone">
        <el-input v-model="form.memberPrice" placeholder="请输入市场价" clearable :readonly="isDetail"/>
      </el-form-item>
      <el-form-item label="库存" prop="phone">
        <el-input v-model="form.stock" placeholder="请输入库存" clearable :readonly="isDetail"/>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-radio-group v-model="form.status" :disabled="isDetail">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="标签" prop="state">
        <el-checkbox-group v-model="form.tags" :readonly="isDetail">
          <el-checkbox label="0">新品</el-checkbox>
          <el-checkbox label="1">推荐</el-checkbox>
          <el-checkbox label="2">热销</el-checkbox>
          <el-checkbox label="3">置顶</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="商品描述" prop="phone">
        <el-input v-model="form.description" placeholder="请输入商品描述" clearable :readonly="isDetail"/>
      </el-form-item>
      <el-form-item label="关键字" prop="phone">
        <el-input v-model="form.keywords" placeholder="请输入关键字" clearable :readonly="isDetail"/>
      </el-form-item>
      <el-form-item label="积分" prop="phone">
        <el-input v-model="form.giftPoint" placeholder="请输入积分" clearable :readonly="isDetail"/>
      </el-form-item>
      <el-form-item label="限用积分" prop="phone">
        <el-input v-model="form.usePointLimit" placeholder="请输入库存" clearable :readonly="isDetail"/>
      </el-form-item>


    </el-form>
    <div slot="footer" class="dialog-footer">
      <template v-if="isDetail">
        <el-button type="primary" @click="dialogVisible=false">关闭</el-button>
      </template>
      <template v-else-if="isAdd">
        <el-button @click="restForm()">取消</el-button>
        <el-button type="primary" @click="submitAddForm()">保存</el-button>
      </template>
      <template v-else-if="isUpdate">
        <el-button @click="restForm()">取消</el-button>
        <el-button type="primary" @click="submitUpdateForm()">修改</el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script>

  import uploadApi from '@/api/system/upload-api'
  import sysProductApi from '@/api/system/sys-product-api'

  const flag = { isflag: '' }

  export default {
    name: 'SysUser',
    components: {},
    props: {
      // detail: 详细页面，add: 添加页面，update：编辑页面
      isDetail: {
        type: Boolean,
        default: false
      },
      isAdd: {
        type: Boolean,
        default: false
      },
      isUpdate: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        dialogVisible: false,
        dialogTitle: null,
        uploadFileList: [],
        form: {
          id: null,
          categoryId: null,
          images: null,
          productName: null,
          originalPrice: null,
          memberPrice: null,
          createTime: null,
          status: null,
          stock: null,
          description: null,
          tags: null,
          masterPicUrl: null,
          keywords: null,
          giftPoint: null,
          deleteFlag: 0,
          usePointLimit: null
        },

        updateId: null,
        departmentOptions: null,
        roleOptions: null,
        treeSelectData: null,
        rules: {
          username: [
            { required: true, message: '请输入用户账号', trigger: 'blur' },
            { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
          ],
          nickname: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { min: 11, max: 11, message: '长度11个字符', trigger: 'blur' }
          ],
          departmentId: [
            { required: true, message: '请选择部门', trigger: 'change' }
          ],
          roleId: [
            { required: true, message: '请选择角色', trigger: 'change' }
          ],
          state: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
          remark: [
            { max: 100, message: '长度100个字符', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {},
    created() {

    },
    mounted() {

    },
    methods: {
      handle(id) {
        if (this.isDetail) {
          this.rules = null;
          this.dialogTitle = '商品信息详情';
          this.getUserDetail(id);
        } else if (this.isAdd) {
          this.dialogTitle = '新增商品信息';
        } else if (this.isUpdate) {
          this.dialogTitle = '修改商品信息';
          this.updateId = id;
          this.getUserDetail(id)
        }
        this.dialogVisible = true
      },
      submitAddForm() {
        console.log("form...")
        this.$refs.sysUserForm.validate((valid) => {
          if (valid) {
            console.log('submit!')
            if (this.uploadFileList.length === 0) {
              this.$message({
                message: '请选择文件',
                type: 'error'
              })
            }
            this.$nextTick(() => {
              this.$refs.upload.submit()
            })
            this.addUser()
            // this.$emit("getList")
          } else {
            console.log('error submit!!')
            return false
          }
        });
      },
      submitUpdateForm() {
        this.$refs.sysUserForm.validate((valid) => {
          if (valid) {
            console.log('submit!')

            if (this.uploadFileList.length === 0) {
              this.$message({
                message: '请选择文件',
                type: 'error'
              })
            }
            this.$nextTick(() => {
              this.$refs.upload.submit()
            })

             this.updateUser()
            // this.$emit("getList")
          } else {
            console.log('error submit!!')
            return false
          }
        });
      },
      getUserDetail(id) {
        sysProductApi.detail(id).then(response => {
          if (response.code === 200) {
            this.form = response.data;
            if (this.isDetail) {
              this.form.roleId = response.data.roleName
            }
            this.departmentName = response.data.departmentName
          }
        });
      },
      addUser() {
        flag.isflag = 1;
        console.log(this.form)
        const addParam = {
          productName: this.form.productName,
          images: this.form.images,
          originalPrice: this.form.originalPrice,
          memberPrice: this.form.memberPrice,
          stock: this.form.stock,
          status: this.form.status,
          tags: this.form.tags,
          description: this.form.description,
          keywords: this.form.keywords,
          giftPoint: this.form.giftPoint,
          createTime: this.form.createTime,
          categoryId: this.form.categoryId,
          masterPicUrl: this.form.masterPicUrl,
          deleteFlag: this.form.deleteFlag,
          usePointLimit: this.form.usePointLimit
        }
        sysProductApi.add(addParam).then(response => {
          if (response.code === 200) {
            this.restForm();
            this.$message({
              message: '保存商品信息成功',
              type: 'success'
            })
            this.$emit('change')
          }
        })
      },
      updateUser() {
        flag.isflag = 2;
        const updateParam = {
          id: this.updateId,
          productName: this.form.productName,
          images: this.form.images,
          originalPrice: this.form.originalPrice,
          memberPrice: this.form.memberPrice,
          stock: this.form.stock,
          status: this.form.status,
          tags: this.form.tags,
          description: this.form.description,
          keywords: this.form.keywords,
          giftPoint: this.form.giftPoint,
          createTime: this.form.createTime,
          categoryId: this.form.categoryId,
          masterPicUrl: this.form.masterPicUrl,
          deleteFlag: this.form.deleteFlag,
          usePointLimit: this.form.usePointLimit
        }
        sysProductApi.update(updateParam).then(response => {
          if (response.code === 200) {
            this.restForm();
            this.$message({
              message: '修改商品信息成功',
              type: 'success'
            })
            this.$emit('change')
          }
        })
      },
      restForm() {
        this.$refs.sysUserForm.resetFields()
        this.dialogVisible = false
      },
      handleChange(file, fileList) {
        // 将最后一个选择的文件赋值给文件列表
        if (fileList && fileList.length > 1) {
          fileList = [file]
        }
        this.uploadFileList = fileList
        this.form.images = URL.createObjectURL(file.raw);
      },
      handleError() {
        this.$message({
          message: '上传错误',
          type: 'error'
        })
      },
      handleBeforeUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('头像大小不能超过 2MB!')
        }
        return isLt2M
      },
      submitForm() {
        if (this.uploadFileList.length === 0) {
          this.$message({
            message: '请选择文件',
            type: 'error'
          })
        }
        this.$nextTick(() => {
          this.$refs.upload.submit()
        })
      },
      resetForm() {
        this.dialogVisible = false
        this.uploadFileList = []
        this.$nextTick(() => {
          this.$refs.upload.clearFiles()
        })
      },
      handleUpload(param) {
        const formData = new FormData()
        formData.append("file", param.file)
        formData.append("type", 'head')
        // 文件上传后，调用修改用户头像方法
        uploadApi.upload(formData).then(response => {
          if (response.code === 200) {
            this.form.images = response.data
          } else {
            throw response.message
          }
        }).then(() => {

        })
      }
    }
  }
</script>

<style lang="scss">
  .sys-user-dialog {
    margin-top: 40px !important;
  }
</style>

<style lang="scss" scoped>

</style>
